<template>
  <view>
    <view class="body">
      <InfoTitleList :infoTitleList="health1"></InfoTitleList>
      
      <view class="hy">
        <view class="hy-text">活跃</view>
        <image class="img" src="/static/imgs/huoyue.png"></image>
      </view>
      
      <InfoTitleList :infoTitleList="health2"></InfoTitleList>
      <!-- 自制环形进度条 -->
      <view class="halo">
        <view v-for="(item, index) in healthData" :key="index" class="halo-box">
          <haloSon :item="item"></haloSon>
        </view>
      </view>
      
      <InfoTitleList :infoTitleList="health3"></InfoTitleList>
      
      <!-- 第一个图表：运动量 -->
      <view class="qxt">
        <uv-tabs
          :list="timeTabs"
          lineHeight="0"
          :activeStyle="{ color: '#4ad795' }"
          :inactiveStyle="{ color: '#aeaeae' }"
          class="xxk"
          :scrollable="false"
          @click="handleTimeTabClick"
        ></uv-tabs>
        <view class="chart-container">
          <!-- 使用 qiun-data-charts 组件，应用运动量图表配置 -->
          <qiun-data-charts
            type="line"
            :opts="chartOptsSport"
            :chartData="sportChartData"
            canvasId="sportChart"
            @touchend="handleChartTouch"
          />
        </view>
      </view>
      
      <InfoTitleList :infoTitleList="health4"></InfoTitleList>
      <!-- 第二个图表：体温 -->
      <view class="qxt">
        <uv-tabs
          :list="timeTabs"
          lineHeight="0"
          :activeStyle="{ color: '#4ad795' }"
          :inactiveStyle="{ color: '#aeaeae' }"
          class="xxk"
          :scrollable="false"
          @click="handleTimeTabClick"
        ></uv-tabs>
        <view class="chart-container">
          <!-- 使用 qiun-data-charts 组件，应用体温图表配置 -->
          <qiun-data-charts
            type="line"
            :opts="chartOptsTemp"
            :chartData="tempChartData"
            canvasId="tempChart"
            @touchend="handleChartTouch"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import Header from '@/components/AppHeader/Header.vue';
import InfoTitleList from '@/components/Animals/InfoTitleList.vue';
import haloSon from '@/components/haloson/haloSon.vue';
import { ref, reactive, onMounted } from 'vue';
import { getHealthInfoNew, getHealthInfo } from '@/api/traceability';

// 获取 Storage 中的 F_Id
const getFIdFromStorage = () => {
  const fId = uni.getStorageSync('F_Id');
  console.log('从 Storage 获取的 F_Id:', fId);
  return fId || null;
};

// 获取健康信息（当前状态）
const fetchHealthInfoNew = async () => {
  const fId = getFIdFromStorage();
  if (!fId) {
    console.error('F_Id 不存在，无法获取健康信息');
    uni.showToast({
      title: 'F_Id 不存在',
      icon: 'error',
    });
    return;
  }
  
  try {
    // 调用接口获取数据
    const response = await getHealthInfoNew({ liveid: fId });
    console.log('获取到的健康信息:', response);
    if (response.code === 200 && response.data && response.data.length > 0) {
      const healthInfo = response.data[0];
      // 更新环形进度条数据
      healthData[0].num = healthInfo.jrbs; // 今日步数作为今日运动量
      healthData[1].num = healthInfo.pjtw; // 平均体温作为当前体温
    }
  } catch (error) {
    console.error('获取健康信息时发生错误:', error);
    uni.showToast({
      title: '获取健康信息失败',
      icon: 'error',
    });
  }
};

// 获取健康信息（历史记录）
const fetchHealthHistory = async () => {
  const fId = getFIdFromStorage();
  if (!fId) {
    console.error('F_Id 不存在，无法获取健康历史信息');
    uni.showToast({
      title: 'F_Id 不存在',
      icon: 'error',
    });
    return;
  }
  
  try {
    // 调用接口获取数据
    const response = await getHealthInfo({ liveid: fId });
    console.log('获取到的健康信息(历史记录):', response);
    if (response.code === 200 && response.data && response.data.length > 0) {
      const historyData = response.data;
      
      // 处理运动量数据
      const sportCategories = historyData.map(item => {
        const date = new Date(item.rq);
        return `${date.getMonth() + 1}-${date.getDate()}`; // 提取月-日
      });
      const sportSeries = historyData.map(item => item.jrbs);
      
      // 处理体温数据
      const tempSeries = historyData.map(item => item.pjtw);
      
      // 更新图表数据
      sportChartData.value = {
        categories: sportCategories,
        series: [
          {
            name: '运动量',
            data: sportSeries,
          },
        ],
      };
      
      tempChartData.value = {
        categories: sportCategories,
        series: [
          {
            name: '体温',
            data: tempSeries,
          },
        ],
      };
    }
  } catch (error) {
    console.error('获取健康历史信息时发生错误:', error);
    uni.showToast({
      title: '获取健康历史信息失败',
      icon: 'error',
    });
  }
};

// 标题列表
const health1 = [{ title: '活跃度' }];
const health2 = [{ title: '健康指标' }];
const health3 = [{ title: '运动量' }];
const health4 = [{ title: '体温' }];

// 环形进度条数据
const healthData = reactive([
  {
    percent: 50,
    size: 312,
    strokeWidth: 9,
    progressColor: '#0bcb75',
    txt: '今日运动量',
    num: 0, // 初始值，将被接口数据替换
  },
  {
    percent: 50,
    size: 312,
    strokeWidth: 9,
    progressColor: '#0bcb75',
    txt: '当前体温',
    num: 0,
    unit: '℃',
  },
]);

// 时间选项卡
const timeTabs = ref([
  { name: '一周内' },
  { name: '一月内' },
  { name: '一年内' },
]);

// 运动量图表配置
const chartOptsSport = reactive({
  color: ['#3eaba0'],
  background: '#FFFFFF',
  padding: [15, 10, 0, 15],
  enableScroll: false,
  legend: { show: false },
  xAxis: {
    disableGrid: false,
    type: 'grid',
    gridColor: '#f7f7f7',
    gridType: 'solid',
    dashLength: 8,
    axisLineColor: '#42aca2',
    fontSize: 8,
    axisLine: { color: '#42aca2' },
  },
  yAxis: {
    gridType: 'solid',
    dashLength: 2,
    splitNumber: 4,
    gridColor: '#f7f7f7',
    axisLine: { show: false },
    data: [
      {
        min: 0,
        max: 1500, // 运动量 Y 轴范围调整为 0-1500
        togix: 1,
        axisLineColor: '#42aca2',
        fontSize: 8,
      },
    ],
  },
  extra: {
    line: {
      type: 'curve',
      width: 2,
      activeType: 'hollow',
    },
  },
  dataLabel: false,
  dataPointShape: true,
  dataPointShapeType: 'hollow',
});

// 体温图表配置
const chartOptsTemp = reactive({
  color: ['#3eaba0'],
  background: '#FFFFFF',
  padding: [15, 10, 0, 15],
  enableScroll: false,
  legend: { show: false },
  xAxis: {
    disableGrid: false,
    type: 'grid',
    gridColor: '#f7f7f7',
    gridType: 'solid',
    dashLength: 8,
    axisLineColor: '#42aca2',
    fontSize: 8,
    axisLine: { color: '#42aca2' },
  },
  yAxis: {
    gridType: 'solid',
    dashLength: 2,
    splitNumber: 4,
    gridColor: '#f7f7f7',
    axisLine: { show: false },
    data: [
      {
        min: 30, // 体温 Y 轴最小值
        max: 42, // 体温 Y 轴最大值
        togix: 1,
        axisLineColor: '#42aca2',
        fontSize: 8,
      },
    ],
  },
  extra: {
    line: {
      type: 'curve',
      width: 2,
      activeType: 'hollow',
    },
  },
  dataLabel: false,
  dataPointShape: true,
  dataPointShapeType: 'hollow',
});

// 运动量图表数据
const sportChartData = ref({
  categories: [],
  series: [
    {
      name: '运动量',
      data: [],
    },
  ],
});

// 体温图表数据
const tempChartData = ref({
  categories: [],
  series: [
    {
      name: '体温',
      data: [],
    },
  ],
});

// 时间选项卡点击事件
const handleTimeTabClick = async (tab) => {
  // 这里可以添加不同时间范围的数据加载逻辑
  // 简化处理，直接调用历史数据获取
  fetchHealthHistory();
};

// 图表触摸事件处理
const handleChartTouch = (e) => {
  console.log('Chart touched:', e);
  // 实现图表触摸交互逻辑
};

// 初始化图表数据
onMounted(() => {
  fetchHealthInfoNew(); // 获取健康信息（当前状态）
  fetchHealthHistory(); // 获取健康信息（历史记录）
});
</script>

<style scoped lang="scss">
.hy {
  width: 750rpx;
  height: 200rpx;
  display: flex;
  .hy-text {
    flex: 1;
    font-size: 38rpx;
    margin-top: 60rpx;
    margin-left: 60px;
    color: #ff6600;
  }
  .img {
    width: 180rpx;
    height: 180rpx;
    margin-right: 77rpx;
    margin-top: -6rpx;
  }
}

.halo {
  width: 750rpx;
  height: 450rpx;
  display: flex;
  .halo-box {
    width: 375rpx;
    height: 450rpx;
  }
}

.qxt {
  width: 750rpx;
  height: 390rpx;
  .chart-container {
    height: 270rpx;
    width: 100%;
    background: #fff;
    padding: 20rpx 0;
  }
}
</style>